import React, { Component } from 'react';
import UserInfo from "../../../../types/UserInfo";
import { FormInstance } from "antd/lib/form";
import UserType from "../../../../types/UserType";
import { addUser } from "../../../../requests/Personal"
import { Button, Card, Form, Input, message, Spin } from "antd";
import { Store, ValidateErrorEntity } from 'rc-field-form/lib/interface'
import { getRes } from "../../../../configFile";

interface IProps { }
interface IState {
    userInfo: UserInfo,
    isLoading: boolean,
}
export default class AddUser extends Component<IProps, IState>{
    formRef = React.createRef<FormInstance>()
    constructor(props: IProps) {
        super(props)
        this.state = {
            isLoading: false,
            userInfo: {
                ID: -1,
                username: '',
                password: '',
                telephone: '',
                email: '',
                lastLoginTimestamp: -1,
                creationTimestamp: -1,
                userType: UserType.DEVICEADMIN
            }
        }
    }

    layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
    };
    tailLayout = {
        wrapperCol: { offset: 4 },
    };

    //输入合法函数
    onFinish: (values: Store) => void = async values => {
        try {
            this.setState({ isLoading: true })
            const res = getRes(await addUser(UserType.DEVICEADMIN, values.username, values.password, values.telephone, values.email))
            if (res.isSuccessful === true) {
                message.success("添加成功")
                this.formRef.current?.resetFields();
            } else {
                console.error(res);
                message.error("添加失败")
            }
            this.setState({ isLoading: false })

        } catch (err) {
            message.error(JSON.stringify(err))
        }
    }

    onFinishFailed = (errorInfo: ValidateErrorEntity) => {
        message.error(errorInfo.errorFields[0].errors[0]);
    };

    render() {
        return (
            <div>
                <Spin size='large' spinning={this.state.isLoading}>
                    <Card
                        title={<span style={{ fontWeight: 'bold' }}>添加用户</span>}
                        bordered={true}>
                        <Form
                            onFinishFailed={this.onFinishFailed}
                            onFinish={this.onFinish}
                            ref={this.formRef}
                            {...this.layout}
                            name="addUser"
                        >

                            <Form.Item
                                label="用户名"
                                name="username"
                                rules={[
                                    {
                                        required: true,
                                        message: '用户名必填',
                                    },
                                ]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                name="password"
                                label="密码"
                                rules={[
                                    {
                                        required: true,
                                        message: '密码必填',
                                    },
                                ]}
                                hasFeedback
                            >
                                <Input.Password />
                            </Form.Item>

                            <Form.Item
                                name="confirm"
                                label="确认密码"
                                dependencies={['password']}
                                hasFeedback={true}
                                rules={[
                                    {
                                        required: true,
                                        message: '确认密码必填',
                                    },
                                    ({ getFieldValue }) => ({
                                        validator(rule, value) {
                                            if (!value || getFieldValue('password') === value) {
                                                return Promise.resolve();
                                            }
                                            return Promise.reject('两次密码输入不一致！');
                                        },
                                    }),
                                ]}
                            >
                                <Input.Password />
                            </Form.Item>

                            <Form.Item
                                label="邮箱"
                                name="email"
                                rules={[{ required: true, message: '请正确填写邮箱格式', type: 'email' }]}

                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                label="电话"
                                name="telephone"
                                rules={[{ required: true, message: '电话不能为空' },
                                ({ getFieldValue }) => ({
                                    validator(rule, value) {
                                        var phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/
                                        if (!value || phoneReg.test(value)) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject('请输入正确电话号码');
                                    },
                                }),
                                ]}
                            >
                                <Input />
                            </Form.Item>


                            <Form.Item {...this.tailLayout}>
                                <Button type="primary" htmlType="submit" size="large">
                                    确认添加
                                </Button>
                            </Form.Item>
                        </Form>
                    </Card>
                </Spin>
            </div>
        )
    }
}